import React, {useCallback, useEffect, useState} from 'react';
import { Input } from 'antd';
import { semicolon } from '../utils/utils';
/*
 *
 * 数值输入框
 * 光标处理问题  https://segmentfault.com/a/1190000016758141
 *  如果遇到需要鼠标离开补两位小数的需求，请把该组件换成 inputNumber
 * */
export const inputNumberValueFromEvent = value => {
  // const value = e.target.value;
  // 清空非数字和点的字符
  const numValue = `${value}`.replace(/[^0-9.-]/g, '');
  // 清空多余的点
  const numValueArr = numValue.split('.');
  let result = numValueArr.length > 1 ? `${numValueArr[0]}.${numValueArr[1]}` : numValueArr[0];
  // 负号
  if (result.slice(0, 1) === '-') {
    result = `${result}`.replace(/-/g, '');
    result = `-${result}`;
  } else {
    result = `${result}`.replace(/-/g, '');
  }
  // 返回
  return result;
};

export const inputNumberValidator = (
  maxLength,
  decimalLength,
  checkZero,
  rule,
  value,
  callback,
) => {
  if (value) {
    const checkVal = `${value}`;
    // 判断长度
    if (checkVal.split('.')[0].replace(/[$\s.,]+/g, '').length > maxLength) {
      callback(`整数不能超过${maxLength}个字符`);
      return;
    }
    // 存在小数点时进行判断
    const decimalSplitArr = checkVal.split('.');
    if (decimalSplitArr.length > 1 && decimalLength === 0) {
      callback(`不能输入小数`);
      return;
    }
    if (decimalSplitArr.length > 1 && decimalSplitArr[1].length > decimalLength) {
      callback(`小数不能超过${decimalLength}位`);
      return;
    }
    // 判断该值不能0
    if (!checkZero && checkVal.replace(/[$\s.,]+/g, '') === '0') {
      callback(`该值不能为0`);
      return;
    }
  }
  if (!checkZero && value === 0) {
    callback('该值不能为0');
    return;
  }
  callback();
};

const InputNumberCustom =(props)=> {
  const [currentValue,setCurrentValue] = useState('');
  const { onChange, value } = props;

  useEffect(()=>{
    setCurrentValue(semicolon(value));
  },[value]);

  const triggerChange = useCallback(e =>{
    // eslint-disable-next-line no-shadow
    if (onChange) {
      const valueTem = String(e.target.value).replace(/\$\s?|(,*)/g, '');
      onChange(inputNumberValueFromEvent(valueTem));
    }

  },[onChange]);

  return (
    <Input
      style={{ textAlign: 'right', width: '100%' }}
      {...props}
      type="text"
      value={currentValue}
      onChange={triggerChange}
    />
  );
}

export default InputNumberCustom;
